/**
 * File:bc.pager.js
 * Youth is just a unoptimized code!
 * -------------------------------------------------------------------------
 * Created by BigQ on 2016/10/8.
 *--------------------------------------------------------------------------
 * This technical information is confidential information,
 * without my written permission is prohibited for commercial purposes.　
 *--------------------------------------------------------------------------
 */
(function ($) {
//分页
    var bcPager = function (ele, opt) {
        this.pageWrap = this.element = $(ele);
        this.pageCount = 0;
        this.toolButtons = [];
        this.defaults = {
            version: 'version 1.0.0',
            pageSize: 20,                          //分页尺寸
            recordCount: 0,
            showFirst: true,
            showLast: true,
            showPrev: true,                             //
            showNext: true,                            //初始化数据
            showWhenever: true,                         //是否分页
            currentPage: 1,                                //当前页
            pageSizeOptions: [10, 20, 30, 40, 50],  //可选择设定的每页结果数
            firstText: '首页',                          //
            lastText: '末页',
            prevText: '上一页',
            nextText: '下一页',
            trunPageEvent: null,
            ellipseText: "...",
            disabledCssClass: 'page_disabled',
            ellipseCssClass: 'page_ellipse',
            firstCssClass: 'page_index',
            lastCssClass: 'page_last',
            prevCssClass: 'page_prev',
            nextCssClass: 'page_next',
            itemCssClass: 'pgae_num',
            itemCurrCssClass: 'this',
            infoCssClass: 'page_info',
            btnCssClass: 'page_btns',
            optCssClass: 'page_opt',
            pageContentCssClass: 'page_box',
            wrapCssClass: 'Framework-page',
            pageInfoTpl: '({currentPage}/{pageCount})页，每页({pageSize})条,共{recordCount}条记录'
        },
            this.options = $.extend({}, this.defaults, opt);
    };
    //bcPager属性
    bcPager.prototype = {
        render: function () {
            this._init();
            return this;
        },
        //初始化
        _init: function () {
            p = this.options;
            if (!this.pageWrap.hasClass(p.wrapCssClass)) {
                this.pageWrap.addClass(p.wrapCssClass);
            }
            if (isNaN(p.pageSize)) {
                this.pageCount = 1;
            }
            else {
                this.pageCount = Math.ceil(p.recordCount / p.pageSize);
            }
            if (this.pageCount == 0) {
                this.pageCount = 1;
            }
            this._builder();

        },
        _builder: function () {
            this.pageContentWrap = $('<div class="' + p.pageContentCssClass + '"> </div>');
            this.toolWrap = $('<div class="tools"></div>');
            this.pageInfoWrap = $('<div class="' + p.infoCssClass + '"> </div>');
            this.pageBtnWrap = $('<div class="' + p.btnCssClass + '"> </div>');
            this.pageOptWrap = $('<div class="' + p.optCssClass + '"> </div>');
            this.pageContentWrap.append(this.pageInfoWrap);
            this.pageContentWrap.append(this.pageBtnWrap);
            this.pageContentWrap.append(this.pageOptWrap);
            this.pageWrap.empty();
            this.pageWrap.append(this.toolWrap);
            this.pageWrap.append(this.pageContentWrap);
            this._getPageInfo();
            this._getPageContent();
            this._getPageOpt();
            this._bindEvent();
        },
        _getPageInfo: function () {
            var g = this, p = this.options;
            var info = p.pageInfoTpl.replace(/\{currentPage\}/g, p.currentPage);
            info = info.replace(/\{pageCount\}/g, g.pageCount);
            info = info.replace(/\{recordCount\}/g, p.recordCount);
            info = info.replace(/\{pageSize\}/g, p.pageSize);
            this.pageInfoWrap.html(info);
        },
        _getPageContent: function () {
            var html = '';
            var g = this, p = this.options;
            if (p.showFirst) {
                html += '<a class="' + p.firstCssClass + '" >' + p.firstText + '</a>';
            }
            if (p.showPrev) {
                html += '<a class="' + p.prevCssClass + '" >' + p.prevText + '</a>';
            }
            if (g.pageCount > 6) {
                html += '<a data-page="1" class="' + p.itemCssClass + '">1</a>';
                if (p.currentPage <= 2) {
                    html += '<a data-page="2" class="' + p.itemCssClass + '">2</a>';
                    html += '<a data-page="3" class="' + p.itemCssClass + '">3</a>';
                    html += '<span class="' + p.ellipseCssClass + '">' + p.ellipseText + '</span>';
                } else if (p.currentPage > 2 && p.currentPage <= g.pageCount - 2) {

                    html += '<span class="' + p.ellipseCssClass + '">' + p.ellipseText + '</span>';
                    html += '<a data-page="' + (p.currentPage - 1) + '" class="' + p.itemCssClass + '">' + (p.currentPage - 1) + '</a>';
                    html += '<a data-page="' + p.currentPage + '" class="' + p.itemCssClass + '">' + p.currentPage + '</a>';
                    html += '<a data-page="' + ( p.currentPage + 1) + '" class="' + p.itemCssClass + '">' + (p.currentPage + 1) + '</a>';
                    html += '<span class="' + p.ellipseCssClass + '">' + p.ellipseText + '</span>';
                } else {
                    html += '<span class="' + p.ellipseCssClass + '">' + p.ellipseText + '</span>';
                    for (var i = g.pageCount - 2; i < g.pageCount; i++) {
                        html += '<a data-page="' + i + '" class="' + p.itemCssClass + '">' + i + '</a>'
                    }
                }
                html += '<a data-page="' + g.pageCount + '" class="' + p.itemCssClass + '">' + g.pageCount + '</a>';
            } else {
                for (var i = 1; i <= g.pageCount; i++) {
                    html += '<a data-page="' + i + '" class="' + p.itemCssClass + '">' + i + '</a>'
                }
            }
            if (p.showNext) {
                html += '<a class="' + p.nextCssClass + '" >' + p.nextText + '</a>';
            }
            if (p.showLast) {
                html += '<a class="' + p.lastCssClass + '" >' + p.lastText + '</a>';
            }
            this.pageBtnWrap.html(html);
            if (p.currentPage == 1) {
                $('.' + p.firstCssClass, this.pageBtnWrap).addClass(p.disabledCssClass);
                $('.' + p.prevCssClass, this.pageBtnWrap).addClass(p.disabledCssClass);
            }
            if (p.currentPage == g.pageCount) {
                $('.' + p.lastCssClass, this.pageBtnWrap).addClass(p.disabledCssClass);
                $('.' + p.nextCssClass, this.pageBtnWrap).addClass(p.disabledCssClass);
            }
            this.pageBtnWrap.find('a[data-page="' + p.currentPage + '"]').addClass(p.itemCurrCssClass).siblings().removeClass(p.itemCurrCssClass);
        },
        _getPageOpt: function () {
            var g = this, p = this.options;
            //select
            var sel = $('<select></select>');
            var str = '';
            for (var i = 0; i < p.pageSizeOptions.length; i++) {
                if (!isNaN(p.pageSizeOptions[i])) {
                    str += '<option value="' + p.pageSizeOptions[i] + '">' + p.pageSizeOptions[i] + '条/页</option>';
                }
                else if ((p.pageSizeOptions[i] + '').toLowerCase() == 'all') {
                    str += '<option value="all">全部</option>';
                }
            }
            sel.html(str);
            sel.val(p.pageSize);
            //go
            var input = $('<input value="" placeholder="页码" title="跳转页码"/><a class="gobt">跳转</a>');
            this.pageOptWrap.html("");
            this.pageOptWrap.append(sel);
            this.pageOptWrap.append(input);
            //事件
            $('select', this.pageOptWrap).change(function () {
                p.pageSize = $(this).val();
                p.currentPage = 1;
                g.render();
                g.goPage();
            });
            $('input', this.pageOptWrap).val(p.currentPage);
            $('input', this.pageOptWrap).click(function () {
                $(this).select();
            }).keydown(function (e) {
                if (e.keyCode == 13) {
                    var current = parseInt($(this).val()) || 1;
                    g.goPage(current);
                }
            });
            $('a', this.pageOptWrap).click(function () {
                var current = parseInt($(this).prev().val()) || 1;
                g.goPage(current);
            });
        },
        _bindEvent: function () {
            var g = this, p = this.options;
            g.pageBtnWrap.on('click', 'a', function (e) {
                if ($(this).hasClass(p.disabledCssClass) || $(this).hasClass(p.itemCurrCssClass)) {
                    return false;
                }
                if ($(this).hasClass(p.firstCssClass)) {
                    p.currentPage = 1;
                }
                else if ($(this).hasClass(p.prevCssClass)) {
                    p.currentPage = Math.max(1, p.currentPage - 1);
                }
                else if ($(this).hasClass(p.nextCssClass)) {
                    p.currentPage = Math.min(g.pageCount, p.currentPage + 1);
                }
                else if ($(this).hasClass(p.lastCssClass)) {
                    p.currentPage = g.pageCount;
                }
                else if ($(this).data('page')) {
                    p.currentPage = parseInt($(this).data('page'));
                }
                g.goPage();
            });
        },
        goPage: function (page) {
            var g = this, p = this.options;
            p.currentPage = page || p.currentPage;
            p.currentPage = Math.max(1, p.currentPage);
            p.currentPage = Math.min(p.currentPage, g.pageCount);
            g._getPageInfo();
            g._getPageContent();
            g._getPageOpt();
            if ($.isFunction(p.trunPageEvent)) {
                p.trunPageEvent(p.currentPage, p.pageSize);
            }
        },
        addToolButton: function (opt) {
            var self = this;
            var def = {
                id: '',
                title: '',
                cssClass: '',
                click: null,
            };
            var option = $.extend({}, def, opt);
            var btn = $('<a class="btn" href="javascript:void(0);"></a>');
            var btnItem = $('<i class="' + option.cssClass + '"> &nbsp; &nbsp;  ' + option.title + '</i>');
            btn.append(btnItem);
            btn.on('click', function () {
                if (option.click && $.isFunction(option.click)) {
                    option.click(option);
                }
            });
            this.toolWrap.append(btn);
            this.toolButtons.push(btn);
        }

    };
    /**
     * BC分页
     * @param options
     * @param grid
     * @returns {*}
     */
    $.fn.bcPager = function (options, grid) {
        var bcPagerPlg = new bcPager(this, options, grid);
        return bcPagerPlg.render();
    };
})(jQuery);